import React, {Component} from 'react';
import BaseOpts from '../BaseOpts';
import './index.css';
import {InputNumber, Slider, Radio, Button, message, Select, Input, Row, Col, Modal, Tabs} from 'antd';
import Ajax from '../../common/ajax';
import AlertInput from '../../common/alertInput';
import Util from '../../common/util';
import SlideInput from '../../common/SlideInput/index';

const Option = Select.Option;

const confirm = Modal.confirm;
const TabPane = Tabs.TabPane;

class MFormOpts extends BaseOpts {

    static defaultProps = {
        data: {
            style: {},
            dataset: {}
        }
    };

    constructor(props) {
        super(props);

        var data = props.data;

        this.state = {
            data: data,
            visible: false,
            tables: [],
            curTable: {
                id: '',
            },
            curTableFields: []
        };

        this._createTable = this._createTable.bind(this);
        this._createTableOk = this._createTableOk.bind(this);
        this._getCurFields = this._getCurFields.bind(this);
        this._delField = this._delField.bind(this);
    }

    render() {
        var _self = this;
        var {data, curTable, curTableFields, tables} = this.state;
        var {style, dataset} = data;
        var marginTop = parseFloat(style.marginTop || 0);
        var marginBottom = parseFloat(style.marginBottom || 0);

        return (
            <div className="optsPanel">
                <div className="optsPanel__item">
                    <label className="optsPanel__item__hd">使用表单</label>
                    <div className="optsPanel__item__bd">
                        {
                            tables && tables.length > 0 ?
                                <Select
                                    defaultValue={curTable.id}
                                    value={curTable.id}
                                    style={{width: 120}}
                                    onSelect={this._selectTable.bind(this)}
                                >
                                    {
                                        tables.map(function (table, index) {
                                            return (
                                                <Option
                                                    key={'table_' + table.id}
                                                    value={table.id}
                                                >{table.name}</Option>
                                            )
                                        })
                                    }
                                </Select>
                                :
                                <a href="/admin/CustomTable/listPage" target="_blank">创建表单</a>
                        }
                    </div>
                </div>

                <div className="optsPanel__item">
                    <label className="optsPanel__item__hd">提交按钮文案</label>
                    <div className="optsPanel__item__bd">
                        <Input
                            defaultValue={dataset.submitText || ''}
                            onInput={(e) => {
                                var val = e.target.value;
                                this.$dataChange('submitText', val, 'dataset');
                            }}
                        />
                    </div>
                </div>

                <div className="optsPanel__item">
                    <label className="optsPanel__item__hd">上外边距</label>
                    <div className="optsPanel__item__bd">
                        <SlideInput step={1} min={0} max={100} value={marginTop} onChange={(val) => {
                            this.$dataChange('marginTop', val + 'px', 'style');
                        }}/>
                    </div>
                </div>

                <div className="optsPanel__item">
                    <label className="optsPanel__item__hd">下外边距</label>
                    <div className="optsPanel__item__bd">
                        <SlideInput step={1} min={0} max={100} value={marginBottom} onChange={(val) => {
                            this.$dataChange('marginBottom', val + 'px', 'style');
                        }}/>
                    </div>
                </div>

                <div className="optsPanel__item">
                    <div className="optsPanel__item__bd">
                        <a href="/admin/CustomTable/listPage" target="_blank"
                           className="ant-btn-dataMng ant-btn ant-btn-primary ant-btn-lg">表单创建与配置</a>
                    </div>
                </div>

                {/*<Tabs defaultActiveKey="1">*/}
                {/*<TabPane tab="表单数据配置" key="1">*/}

                {/*<div className="optsPanel__item optsPanel__item_auto">*/}
                {/*<div className="optsPanel__item__bd">*/}
                {/*<div className="fieldListHeader">*/}
                {/*<Select*/}
                {/*defaultValue={curTable.id}*/}
                {/*value={curTable.id}*/}
                {/*style={{width: 120}}*/}
                {/*onSelect={this._selectTable.bind(this)}*/}
                {/*>*/}
                {/*{*/}
                {/*tables.map(function (table, index) {*/}
                {/*return (*/}
                {/*<Option*/}
                {/*key={'table_' + table.id}*/}
                {/*value={table.id}*/}
                {/*>{table.name}</Option>*/}
                {/*)*/}
                {/*})*/}
                {/*}*/}
                {/*</Select>*/}

                {/*<Button*/}
                {/*onClick={this._createTable}*/}
                {/*>创建表单</Button>*/}

                {/*{curTable.id ?*/}
                {/*(*/}
                {/*<Button*/}
                {/*onClick={_self._createFields.bind(this)}*/}
                {/*>添加表单项</Button>*/}
                {/*)*/}
                {/*: null*/}
                {/*}*/}
                {/*</div>*/}


                {/*{*/}
                {/*curTable && curTable.id ?*/}
                {/*(*/}
                {/*<div className="fieldListWrap">*/}
                {/*<ul className="fieldList">*/}
                {/*{*/}
                {/*curTableFields.map(function (field, index) {*/}
                {/*return (*/}
                {/*<li className="fieldItem"*/}
                {/*key={'field_' + (field.id || field.uid)}>*/}
                {/*<Row gutter={8}>*/}
                {/*<Col span={6}>*/}
                {/*<Input*/}
                {/*onInput={*/}
                {/*(evt) => {*/}
                {/*_self._onFieldNameInput(index, evt.target.value);*/}
                {/*}*/}
                {/*}*/}
                {/*placeholder={'表单项名称'}*/}
                {/*value={field.value}*/}
                {/*/>*/}
                {/*</Col>*/}
                {/*<Col span={8}>*/}
                {/*<Input*/}
                {/*onInput={*/}
                {/*(evt) => {*/}
                {/*_self._onFieldTipInput(index, evt.target.value);*/}
                {/*}*/}
                {/*}*/}
                {/*placeholder={'表单项提示语'}*/}
                {/*value={field.content}*/}
                {/*/>*/}
                {/*</Col>*/}
                {/*<Col span={6}>*/}
                {/*<Select*/}
                {/*defaultValue={field.type}*/}
                {/*onSelect={(val) => {*/}
                {/*field.type = val;*/}
                {/*_self.setState({*/}
                {/*curTableFields: _self.state.curTableFields*/}
                {/*});*/}
                {/*}}*/}
                {/*>*/}
                {/*<Option value={'0'}>单文本</Option>*/}
                {/*<Option value={'1'}>多文本</Option>*/}
                {/*</Select>*/}
                {/*</Col>*/}
                {/*<Col span={4}>*/}
                {/*<Button*/}
                {/*onClick={() => {*/}
                {/*_self._delField(field);*/}
                {/*}}*/}
                {/*type="danger"*/}
                {/*size={'small'}*/}
                {/*>删除</Button>*/}
                {/*</Col>*/}
                {/*</Row>*/}
                {/*</li>*/}
                {/*)*/}
                {/*})*/}
                {/*}*/}
                {/*</ul>*/}

                {/*<div className="fieldListOpts">*/}
                {/*<Button*/}
                {/*onClick={this._createFieldsOk.bind(this)}*/}
                {/*type={'primary'}*/}
                {/*>保存</Button>*/}
                {/*</div>*/}
                {/*</div>*/}
                {/*)*/}
                {/*: null*/}
                {/*}*/}
                {/*</div>*/}
                {/*</div>*/}
                {/*</TabPane>*/}
                {/*<TabPane tab="表单样式" key="2">*/}
                {/**/}
                {/*</TabPane>*/}
                {/*</Tabs>*/}


                <AlertInput
                    visible={this.state.visible}
                    title={'创建表单'}
                    placeholder={'请输入表单名称'}
                    onOk={this._createTableOk}
                    onCancel={this._crateTableCancel.bind(this)}
                />
            </div>
        );
    }

    componentDidMount() {
        var {curTable} = this.state;

        this._getTables();
    }

    _getTables() {
        var _self = this;
        var {data} = this.state;

        Ajax.G('/admin/CustomTable/getTableList', {}, function (res) {
            var tableList = res.result.tableList;
            var tables = [];
            var curTableId;

            tableList.forEach(function (tb) {
                tables.push({
                    id: tb.id,
                    name: tb.table_name,
                });
            });

            curTableId = data['dataset']['tableId'] || (tables[0] && tables[0].id);

            if (curTableId) {
                _self._getCurFields(curTableId);
            }

            _self.setState({
                tables,
            }, function () {
                _self.setState({
                    curTable: {
                        id: curTableId
                    }
                })
            });
        });
    }

    _createTable() {
        this.setState({
            visible: true
        });
    }

    _createTableOk(name) {
        var _self = this;

        if (!name) {
            return message.error('创建表单失败，请输入表单名称哦');
        }
        Ajax.P('/admin/CustomTable/createTable', {
            tableName: name
        }, function (res) {
            var result = res.result;
            var {tables} = _self.state;

            tables.push({
                id: result.tableId,
                name
            })
            _self.setState({
                visible: false,
                tables
            });
        });
    }

    _crateTableCancel() {
        var _self = this;

        _self.setState({
            visible: false,
        });
    }

    _selectTable(id) {
        var _self = this;
        var {tables} = this.state;
        var curTable;

        tables.some(function (tb) {
            if (tb.id == id) {
                curTable = tb;
                return true;
            }
        });
        this.setState({
            curTable
        });
        this._getCurFields(id, function (tableId, valueList) {
            _self.$dataChange('tableId', tableId, 'dataset');
            _self.$dataChange('_fieldList', valueList, 'dataset');
        });
    }

    _getCurFields(formId, cb) {
        var _self = this;

        Ajax.G('/admin/CustomTable/getTableValue', {
            tableId: formId
        }, function (res) {
            var valueList = res.result.valueList || [];

            _self.setState({
                curTableFields: valueList
            });

            cb && cb(formId, valueList || []);
        });
    }

    _createFields() {
        var {curTableFields} = this.state;

        curTableFields.push({
            uid: Util.getUId(),
            id: 0,
            type: '0',
            value: '',
            keyname: '',
            content: '',
        });
        this.setState({
            curTableFields,
        });
    }

    _createFieldsOk() {
        var _self = this;
        var {curTable, curTableFields} = this.state;
        var ids = [], values = [], contents = [], types = [];

        curTableFields = curTableFields || [];
        curTableFields.forEach(function (fieldObj) {
            ids.push(fieldObj.id || 0);
            values.push(fieldObj.value || '');
            contents.push(fieldObj.content || '');
            types.push(fieldObj.type || 0);
        });

        Ajax.P('/admin/CustomTable/addTableValue', {
            tableId: curTable.id,
            ids: ids.join(','),
            values: values.join(','),
            contents: contents.join(','),
            types: types.join(','),
        }, function (res) {
            _self._getCurFields(curTable.id, function (tableId, valueList) {
                _self.$dataChange('_fieldList', valueList, 'dataset');
            });
            message.success('表单配置存在成功！');
        });
    }

    _delField(item) {
        var _self = this;
        var {curTable, curTableFields} = this.state;
        var id = item.id;

        if (!id || id == 0) {
            curTableFields.some(function (field, index) {
                if (field.uid == item.uid) {
                    curTableFields.splice(index, 1);
                    return true;
                }
            });
            _self.setState({
                curTableFields
            });
            return;
        }

        confirm({
            title: '您确定删除该表单项吗?',
            onOk() {
                Ajax.P('/admin/CustomTable/deleteTableValue', {
                    tableId: curTable.id,
                    ids: id + '',
                }, function (res) {

                    curTableFields.some(function (field, index) {
                        if (field.id == id) {
                            curTableFields.splice(index, 1);
                            return true;
                        }
                    });

                    _self.setState({
                        curTableFields
                    });
                    _self.$dataChange('_fieldList', curTableFields, 'dataset');
                });
            },
            onCancel() {
            },
        });
    }

    _onFieldNameInput(index, val) {
        var {curTableFields} = this.state;

        curTableFields[index].value = val;

        this.setState({
            curTableFields
        });
    }

    _onFieldTipInput(index, val) {
        var {curTableFields} = this.state;

        curTableFields[index].content = val;

        this.setState({
            curTableFields
        });
    }
}

export default MFormOpts;
